<?php

namespace app\admin\controller;

use app\common\model\UsersModel;
use app\common\model\RoleModel;
use app\common\model\UserRoleModel;
use think\facade\Request;
use think\Db;

class UserController extends AdminBase
{
    public function lists(UsersModel $users)
    {
        if ($this->request->isAjax()) {
            $pageSize = $this->getPageSize();
            $page = $this->getPage();
            $where = '';
            if($this->app->user->username != 'admin') {
                $where = "u.username='{$this->app->user->username}'";
            }
            $data = Db::field(['u.uid', 'u.username', 'u.status', 'GROUP_CONCAT(r.role_name)' => 'roleName'])
                ->table(['users' => 'u', 'user_role' => 'ur', 'role' => 'r'])
                ->where('u.uid=ur.uid AND ur.role_id=r.role_id')
                ->where($where)
                ->group('u.uid')
                ->paginate($pageSize);

            $lists = $data->items();
            foreach ($lists as $key=>$value){
                $lists[$key]['adminName'] = $this->app->user->username;
            }
            $total = $data->total();
            return $this->listJson($lists, $total);
        } else {
            return view();
        }
    }

    public function add(){
        if ($this->request->isAjax()) {
            $userData = Request::param();
            //用户名是否重复
            $user = UsersModel::where('username','=',$userData['username'])->find();
            if(isset($user)) return $this->errJson('用户名已存在,请重新输入');
            //设置密码
            if($userData['pwd1'] != $userData['pwd2']){
                return $this->errJson('密码输入不一致');
            }
            $userData['password'] = password_hash($userData['pwd1'],PASSWORD_DEFAULT);
            $res = UsersModel::create($userData);

            $roleIds = explode(',', $userData['roleId']);
            $data = [];
            foreach ($roleIds as $key => $value){
                $data[] = ['uid' => $res->uid, 'role_id' => $value];
            }
            $UserRole = new UserRoleModel();
            $pr = $UserRole->saveAll($data, false);
            if(isset($pr)){
                return $this->okJson('添加成功');
            }else{
                return $this->errJson('添加失败');
            }
        } else {
            $role = RoleModel::select();
            $this->assign('roles', $role);
            return view();
        }
    }

    //编辑用户
    public function edit(){
        $uid = input('uid');
        if ($this->request->isAjax()) {
            $name = input('username');
            $roleId = input('roleId');
            if(empty($name) || empty($roleId) || empty($uid)) return $this->errJson('缺少参数');
            $user = UsersModel::where('uid', $uid)->find();

            if($user['username'] != $name){
                $roles = RoleModel::where('role_name', $name)->find();
                if(!empty($roles)) return $this->errJson('角色已存在');
            }
            $user = UsersModel::update(['username' => $name], ['uid' => $uid]);
            $roleId = trim($roleId, ',');
            $roleIds = explode(',', $roleId);
            $data = [];
            foreach ($roleIds as $key => $value){
                $data[] = ['uid' => $uid, 'role_id' => $value];
            }
            $UserRole = new UserRoleModel();
            $UserRole->where('uid', $uid)->delete();
            $pr = $UserRole->saveAll($data, false);
            if($pr) {
                return $this->okJson('ok');
            } else {
                return $this->errJson('error');
            }
        }else{
            $user = UsersModel::get($uid);
            $role = RoleModel::select();
            $myRoles = UserRoleModel::where('uid', $uid)->field('role_id')->select()->toArray();
            $myRoles = array_column($myRoles, 'role_id');
            $this->assign('user',$user);
            $this->assign('roles', $role);
            $this->assign('myRoles', $myRoles);
            return view();
        }
    }

    public function editPwd(UsersModel $users){
        $uid = input('uid');
        if ($this->request->isAjax()) {
            $oldPwd = input('oldPwd');
            $newPwd = input('newPwd');
            $newPwd1 = input('newPwd1');
            if ($newPwd != $newPwd1) {
                $this->errJson('密码不一致');
            }
            $user = $this->app->user;
            if ($user['uid'] != $uid) {
                return $this->errJson('没有权限修改此用户密码');
            }
            $user = $users->where([ 'uid' => $uid])->find();
            if (empty($user) || empty(password_verify($oldPwd, $user->password))) return $this->errJson('旧密码不正确');
            $pwd = password_hash($newPwd, PASSWORD_DEFAULT);
            $result = UsersModel::update(['password' => $pwd], ['uid' => $uid]);
            if ($result) {
                session(null);
                return $this->okJson('修改成功');
            } else {
                return $this->errJson('失败');
            }
        }else{
            $this->assign('uid', $uid);
            return view();
        }
    }

    public function reset()
    {
        $uid = input('uid');
        $pwd = password_hash('123456', PASSWORD_DEFAULT);
        $result = UsersModel::update(['password' => $pwd], ['uid' => $uid]);
        if ($result) {
            return $this->okJson('重置成功');
        } else {
            return $this->errJson('失败');
        }
    }

    public function editStatus()
    {
        $uid = input('uid');
        $status = input('status');
        $result =UsersModel::update(['status'=>$status],['uid'=>$uid]);
        if($result) {
            return $this->okJson('成功');
        }else{
            return $this->errJson('失败');
        }
    }

    //删除
    public function del(){
        $id = input('uid');
        $result = UsersModel::destroy($id);
        return $this->okJson('ok');
    }
}